import 'dart:convert';

import 'package:flutter/services.dart';
import 'package:lib_core/lib_core.dart';
import 'package:lib_core/multi_engine/gt_multi_engine_sync.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';

/// An implementation of [PlatformInterface] that uses method channels.
class GTLibCoreMethodChannel extends PlatformInterface {

  static final Object _token = Object();

  static final GTLibCoreMethodChannel _instance = GTLibCoreMethodChannel._();

  /// The default instance of [LibUtilsPlatform] to use.
  ///
  /// Defaults to [GTLibCoreMethodChannel].
  static GTLibCoreMethodChannel get instance => _instance;

  /// The method channel used to interact with the native platform.
  final _methodChannel = const MethodChannel('com.gateio.flutter.lib_core.MethodChannel');

  /// Constructs a GTLibCoreMethodChannel.
  GTLibCoreMethodChannel._() : super(token: _token) {
    // 监听原生侧 方法调用
    _methodChannel.setMethodCallHandler((call) async {
      GTLogger.debug("GTLibCoreMethodChannel flutter onCall: ${call.toString()}");

      // 监听 原生侧转发其他引擎同步通知
      if (call.method == "listenMultiEngineSync") {
        if (call.arguments == null || call.arguments !is Map<String, dynamic>) {
          GTLogger.error("GTLibCoreMethodChannel: The arguments is invalid.");
          return;
        }
        GTMultiEngineSyncer.dispatchListens(Map<String, dynamic>.from(call.arguments));
      }
    });
  }

  Future<bool> notifyMultiEngineSync(Map<String, dynamic> arguments) async {
    GTLogger.debug("GTLibCoreMethodChannel notifyMultiEngineSync: ${jsonEncode(arguments)}");

    final result = await _methodChannel.invokeMethod<bool>('notifyMultiEngineSync', arguments);
    return result ?? false;
  }

}
